<template>
	<view class="circle-detail">
		<!-- 圈子信息卡片 -->
		<CircleInfoCard :circleInfo="circleInfo" :joinedCircles="joinedCircles" @joinCircle="handleJoinCircle"
			@leaveCircle="handleLeaveCircle" @shareCircle="handleShareCircle" />

		<!-- 标签页切换 -->
		<view class="tab-container">
			<view class="tab-wrapper">
				<view class="tab-item" :class="{ active: activeTab === 'posts' }" @click="switchTab('posts')">
					<text>帖子</text>
					<text class="tab-count">{{ circleInfo?.postCount || 0 }}</text>
				</view>
				<view class="tab-item" :class="{ active: activeTab === 'members' }" @click="switchTab('members')">
					<text>成员</text>
					<text class="tab-count">{{ circleInfo?.memberCount || 0 }}</text>
				</view>
			</view>
		</view>

		<!-- 内容区域 -->
		<view class="content-container">
			<!-- 帖子列表 -->
			<view v-if="activeTab === 'posts'" class="posts-content">
				<WaterfallList v-if="posts.length > 0" :posts="posts" :itemWidth="160" @postClick="handlePostClick" />
				<view v-else class="empty-state">
					<text class="empty-text">暂无帖子</text>
				</view>
			</view>

			<!-- 成员列表 -->
			<view v-if="activeTab === 'members'" class="members-content">
				<MemberTab v-if="members.length > 0" :members="members" @memberClick="handleMemberClick"
					@moreActions="handleMemberMoreActions" />
				<view v-else class="empty-state">
					<text class="empty-text">暂无成员</text>
				</view>
			</view>
		</view>

		<!-- 加载状态 -->
		<view v-if="loading" class="loading-container">
			<text class="loading-text">加载中...</text>
		</view>
	</view>
</template>

<script setup lang="ts">
	import { onLoad } from '@dcloudio/uni-app';
	import { ref, onMounted } from 'vue';
	import {
		getCircleDetail, getMemberList, getJoinedCircle,
		getCurrentUserRole, setBlacklistMember, removeMember,
		updateTransferOwner, leaveCircle, joinCircle,
		type CircleBasicInfo, type CircleMemberRelation
	} from '@/api/circle/circle'
	import { getPostByCircleId, type PostBasicInfo } from '@/api/post/post'
	import CircleInfoCard from './components/CircleInfoCard.vue'
	import WaterfallList from '@/components/post/WaterfallList.vue'
	import MemberTab from './components/MemberTab.vue'
	import useUserStore from '@/store/modules/user';

	const circleId = ref<number>()
	const circleInfo = ref<CircleBasicInfo>()
	const posts = ref<PostBasicInfo[]>([])
	const members = ref<CircleMemberRelation[]>([])
	const activeTab = ref<'posts' | 'members'>('posts')
	const loading = ref(false)

	const userId = ref(useUserStore().user.userId)
	const joinedCircles = ref([])

	const myRole = ref()

	const getJoinedCircleByUserId = async () => {
		const res = await getJoinedCircle(userId.value)
		joinedCircles.value = res.data
	}

	// 页面加载时获取参数
	onLoad(async (options) => {
		if (options?.id) {
			circleId.value = Number(options.id)
			myRole.value = (await getCurrentUserRole(circleId.value)).data
		}
	})

	const refreshData = () => {
		loadCircleData()
		getJoinedCircleByUserId()
	}

	onMounted(() => {
		if (circleId.value) {
			refreshData()
		}
	})

	// 加载圈子数据
	const loadCircleData = async () => {
		if (!circleId.value) return

		loading.value = true
		try {
			// 并行获取圈子信息、帖子和成员数据
			const [circleRes, postsRes, membersRes] = await Promise.all([
				getCircleDetail(circleId.value),
				getPostByCircleId(circleId.value),
				getMemberList(circleId.value)
			])

			circleInfo.value = circleRes.data
			posts.value = postsRes.rows || []
			members.value = membersRes.rows || []
		} catch (error) {
			console.error('加载圈子数据失败:', error)
			uni.showToast({
				title: '加载失败',
				icon: 'error'
			})
		} finally {
			loading.value = false
		}
	}

	// 切换标签页
	const switchTab = (tab : 'posts' | 'members') => {
		activeTab.value = tab
	}

	// 处理帖子点击
	const handlePostClick = (post : PostBasicInfo) => {
		uni.navigateTo({
			url: `/pages/post/postDetail?id=${post.id}`
		})
	}

	// 处理成员点击
	const handleMemberClick = (member : CircleMemberRelation) => {
		uni.navigateTo({
			url: `/pages/author/authorDetail?id=${member.userId}`
		})
	}

	// 处理成员更多操作
	const handleMemberMoreActions = (member : CircleMemberRelation) => {
		let itemList : string[] = [];
		if (member.memberRole === 3 || myRole.value === 1 || myRole.value === 2) {
			itemList = ['查看资料'];
		} else if (member.memberStatus === 1 && member.blacklistStatus === 0) {
			itemList = ['查看资料', '拉入黑名单', '移除成员', '转让圈主'];
		} else if (member.memberStatus === 2 && member.blacklistStatus === 1) {
			itemList = ['查看资料', '移出黑名单'];
		}
		uni.showActionSheet({
			itemList,
			success: (res) => {
				// 获取选中的操作名称
				const selectedAction = itemList[res.tapIndex];
				switch (selectedAction) {
					case '查看资料':
						handleMemberClick(member)
						break
					case '拉入黑名单':
						handleBlacklistMember(member, 1)
						break
					case '移出黑名单':
						handleBlacklistMember(member, 0)
						break
					case '移除成员':
						handleRemoveMember(member)
						break
					case '转让圈主':
						handleTransfer(member)
						break
				}
			}
		})
	}

	//转让圈主
	const handleTransfer = (member : CircleMemberRelation) => {
		uni.showModal({
			title: '确认操作',
			content: `确定要转让圈主给 ${member.nickName} 吗？`,
			success: async (res) => {
				if (res.confirm) {
					// 调用转让圈主的API
					console.log('转让圈主:', member)
					await updateTransferOwner(member.circleId, member.userId, member.nickName)
					refreshData()
					uni.showToast({
						title: '操作成功',
						icon: 'success'
					})
				}
			}
		})
	}

	// 拉入黑名单或拉出黑名单
	const handleBlacklistMember = (member : CircleMemberRelation, status : number) => {
		let content = ''
		if (member.blacklistStatus === 0) {
			content = `确定要将 ${member.nickName} 拉入黑名单吗？`
		} else {
			content = `确定要将 ${member.nickName} 移出黑名单吗？`
		}
		uni.showModal({
			title: '确认操作',
			content: content,
			success: async (res) => {
				if (res.confirm) {
					// 调用拉入黑名单的API
					console.log('拉入黑名单:', member)
					await setBlacklistMember(member.circleId, member.userId, status)
					refreshData()
					uni.showToast({
						title: '操作成功',
						icon: 'success'
					})
				}
			}
		})
	}

	// 移除成员
	const handleRemoveMember = (member : CircleMemberRelation) => {
		uni.showModal({
			title: '确认操作',
			content: `确定要移除成员 ${member.nickName} 吗？`,
			success: async (res) => {
				if (res.confirm) {
					// 调用移除成员的API
					console.log('移除成员:', member)
					await removeMember(member.circleId, member.userId)
					refreshData()
					uni.showToast({
						title: '操作成功',
						icon: 'success'
					})
				}
			}
		})
	}

	// 处理加入圈子
	const handleJoinCircle = (circleInfo : CircleBasicInfo) => {
		uni.showModal({
			title: '加入圈子',
			content: `确定要加入 ${circleInfo.circleName} 吗？`,
			success: async (res) => {
				if (res.confirm) {
					try {
						// 调用加入圈子的API
						console.log('加入圈子:', circleInfo)
						await joinCircle(circleInfo.id)
						uni.showToast({
							title: '加入成功',
							icon: 'success'
						})
						// 刷新数据
						refreshData()
					} catch (error) {
						console.error('加入圈子失败:', error)
						uni.showToast({
							title: '操作失败',
							icon: 'error'
						})
					}
				}
			}
		})
	}

	// 处理退出圈子
	const handleLeaveCircle = (circleInfo : CircleBasicInfo) => {
		uni.showModal({
			title: `退出 ${circleInfo.circleName} 圈子`,
			content: `确定要退出吗？`,
			success: async (res) => {
				if (res.confirm) {
					try {
						// 调用退出圈子的API
						console.log('退出圈子:', circleInfo)
						await leaveCircle(circleInfo.id)
						uni.showToast({
							title: '已退出圈子',
							icon: 'success'
						})
						// 刷新数据
						refreshData()
					} catch (error) {
						uni.showToast({
							title: error.message,
							icon: 'error'
						})
					}
				}
			}
		})
	}

	// 处理分享圈子
	const handleShareCircle = (circleInfo : CircleBasicInfo) => {
		uni.showActionSheet({
			itemList: ['分享到微信', '分享到朋友圈', '复制链接'],
			success: (res) => {
				switch (res.tapIndex) {
					case 0:
						// 分享到微信
						uni.showToast({
							title: '分享到微信',
							icon: 'none'
						})
						break
					case 1:
						// 分享到朋友圈
						uni.showToast({
							title: '分享到朋友圈',
							icon: 'none'
						})
						break
					case 2:
						// 复制链接
						uni.setClipboardData({
							data: `圈子链接: ${circleInfo.circleName}`,
							success: () => {
								uni.showToast({
									title: '链接已复制',
									icon: 'success'
								})
							}
						})
						break
				}
			}
		})
	}
</script>

<style lang="scss" scoped>
	.circle-detail {
		min-height: 100vh;
		background-color: #f7f7f7;
	}

	.tab-container {
		background: white;
		padding: 0 24rpx;
		border-bottom: 1rpx solid #eee;

		.tab-wrapper {
			display: flex;

			.tab-item {
				flex: 1;
				display: flex;
				align-items: center;
				justify-content: center;
				gap: 8rpx;
				padding: 24rpx 0;
				font-size: 28rpx;
				color: #666;
				position: relative;
				cursor: pointer;
				transition: all 0.3s ease;

				&.active {
					color: #007AFF;
					font-weight: 600;

					&::after {
						content: '';
						position: absolute;
						bottom: 0;
						left: 50%;
						transform: translateX(-50%);
						width: 60rpx;
						height: 4rpx;
						background: #007AFF;
						border-radius: 2rpx;
					}
				}

				.tab-count {
					font-size: 24rpx;
					background: #f0f0f0;
					color: #999;
					padding: 2rpx 8rpx;
					border-radius: 12rpx;
					min-width: 32rpx;
					text-align: center;
				}

				&.active .tab-count {
					background: #007AFF;
					color: white;
				}
			}
		}
	}

	.content-container {
		flex: 1;
	}

	.posts-content,
	.members-content {
		min-height: 400rpx;
	}

	.empty-state {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 400rpx;

		.empty-text {
			font-size: 28rpx;
			color: #999;
		}
	}

	.loading-container {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 200rpx;

		.loading-text {
			font-size: 28rpx;
			color: #999;
		}
	}
</style>